<template>
  <div class="dashboard-editor-container">
    <el-card class="box-card">
      <div class="title">日期选择</div>
      <!-- <el-date-picker
        v-model="dateRange"
        type="daterange"
        @change="handleChange"
        value-format="yyyy-MM-dd"
        format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :disabled-date="disabledDate"
      >
      </el-date-picker> -->
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :disabled-date="disabledDate"
        @change="handleChange"
        value-format="yyyy-MM-dd"
        format="yyyy-MM-dd"
      >
      </el-date-picker>
    </el-card>
    <el-card class="box-card">
      <div class="title">用户统计</div>
      <el-row :gutter="40" class="panel-group">
        <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
          <div class="card-panel" @click="handleSetLineChartData('newVisitis')">
            <div class="card-panel-description">
              <div class="card-panel-text">注册用户</div>
              <count-to
                :start-val="0"
                :end-val="userAllCount"
                :duration="2600"
                class="card-panel-num"
              />
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
          <div class="card-panel">
            <div class="card-panel-description">
              <div class="card-panel-text">实名认证</div>
              <count-to
                :start-val="0"
                :end-val="userAuthCount"
                :duration="3000"
                class="card-panel-num"
              />
            </div>
          </div>
        </el-col>
        <!-- <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
          <div class="card-panel">
            <div class="card-panel-description">
              <div class="card-panel-text">今日注册</div>
              <count-to
                :start-val="0"
                :end-val="userCountData.todayCount"
                :duration="3200"
                class="card-panel-num"
              />
            </div>
          </div>
        </el-col>
  
        <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
          <div class="card-panel">
            <div class="card-panel-description">
              <div class="card-panel-text">今日认证</div>
              <count-to
                :start-val="0"
                :end-val="userCountData.todayAuthCount"
                :duration="3200"
                class="card-panel-num"
              />
            </div>
          </div>
        </el-col> -->
      </el-row>
    </el-card>

    <el-card class="box-card">
      <div class="title">数据概况</div>

      <el-row
        style="background: #fff; padding: 16px 16px 0; margin-bottom: 32px"
      >
        <line-chart :chart-data="lineChartData" />
      </el-row>
    </el-card>
  </div>
</template>
  
  <script>
import {
  countUser,
  statisticsUserCount,
  countListByDay,
} from "../../api/dashboard";
import echarts from "echarts";
import CountTo from "vue-count-to";

import LineChart from "./components/LineChart";
// const lineChartData = {
//   newVisitis: {
//     expectedData: [100, 120, 161, 134, 105, 160, 165],
//     actualData: [120, 82, 91, 154, 162, 140, 145],
//   },
//   messages: {
//     expectedData: [200, 192, 120, 144, 160, 130, 140],
//     actualData: [180, 160, 151, 106, 145, 150, 130],
//   },
//   purchases: {
//     expectedData: [80, 100, 121, 104, 105, 90, 100],
//     actualData: [120, 90, 100, 138, 142, 130, 130],
//   },
//   shoppings: {
//     expectedData: [130, 140, 141, 142, 145, 150, 160],
//     actualData: [120, 82, 91, 154, 162, 140, 130],
//   },
// };

export default {
  components: {
    CountTo,
    LineChart,
  },
  data() {
    return {
      userCountData: {
        allCount: 0,
        authCount: 0,
        todayAuthCount: 0,
        todayCount: 0,
      },
      dateRange: [], // 选择的日期范围
      userAllCount: 0,
      userAuthCount: 0,
      lineChartData: {
        assayOrderWeekCount: [],
        checkOrderWeekCount: [],
        serviceOrderCount: [],
        myTime: [],
      },
    };
  },

  created() {
    this.setDefaultDateRange();
    countUser().then((response) => {
      this.userCountData = response.data.data;
    });
    

    statisticsUserCount({
      end: this.dateRange[1],
      start: this.dateRange[0],
    }).then((response) => {
      //   console.log(response.data.data);
      this.userAllCount = response.data.data.userAllCount;
      this.userAuthCount = response.data.data.userAuthCount;
    });

    countListByDay({
      end: this.dateRange[1],
      start: this.dateRange[0],
    }).then((response) => {
      //   console.log(response.data.data);
      this.setChartData(response.data.data);
    });
  },
  methods: {
    handleSetLineChartData(type) {
      this.$emit("handleSetLineChartData", type);
    },
    setDefaultDateRange() {
      const end = new Date();
      const start = new Date();
      start.setDate(end.getDate() - 6); // 最近7天，包括今天

      // 将日期格式化为 yyyy-MM-dd
      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      };

      this.dateRange = [formatDate(start), formatDate(end)];
    },
    disabledDate(date) {
      const today = new Date();
      today.setHours(0, 0, 0, 0); // 将时间部分设置为 00:00:00

      const twelveMonthsLater = new Date();
      twelveMonthsLater.setMonth(today.getMonth() + 12); // 12个月后的日期
      twelveMonthsLater.setHours(0, 0, 0, 0); // 将时间部分设置为 00:00:00

      // 禁用今天之前的日期
      if (date < today) {
        return true;
      }

      // 禁用12个月后的日期
      if (date > twelveMonthsLater) {
        return true;
      }

      return false;
    },
    setChartData(v) {
      //   console.log(v);
      let userList = v.userList;
      let authList = v.authList;
      this.lineChartData.myTime = [];
      this.lineChartData.assayOrderWeekCount = [];
      this.lineChartData.checkOrderWeekCount = [];

      // 获取所有唯一的日期
      const allDays = [
        ...new Set([
          ...userList.map((item) => item.day),
          ...authList.map((item) => item.day),
        ]),
      ];
      // 判断无数据处理
      if (allDays.length == 0) {
        this.lineChartData.myTime = [];
        this.lineChartData.assayOrderWeekCount = [];
        this.lineChartData.checkOrderWeekCount = [];
        return false;
      }
      this.lineChartData.myTime = allDays;


      // 将 userList 和 authList 转换为以 day 为键的对象
      const userMap = userList.reduce((acc, curr) => {
        acc[curr.day] = curr.userCount;
        return acc;
      }, {});

      const authMap = authList.reduce((acc, curr) => {
        acc[curr.day] = curr.userAuthCount;
        return acc;
      }, {});

      // 合并数据
      const result = allDays.map((day) => ({
        day,
        userCount: userMap[day] || 0, // 如果 userMap 中没有该日期，则 userCount 为 0
        userAuthCount: authMap[day] || 0, // 如果 authMap 中没有该日期，则 userAuthCount 为 0
      }));

      result.forEach((item) => {
        this.lineChartData.assayOrderWeekCount.push(item.userCount);
        this.lineChartData.checkOrderWeekCount.push(item.userAuthCount);
      });

      // 输出结果
      console.log("jieguo----------" + result);
    },
    handleChange(dateRange) {
      if (dateRange && dateRange.length === 2) {
        const [startDate, endDate] = dateRange;
        const start = new Date(startDate);
        const end = new Date(endDate);
        const twelveMonthsLater = new Date(start);
        twelveMonthsLater.setMonth(start.getMonth() + 12); // 开始日期后的12个月

        // 如果结束日期超过12个月，则自动调整为12个月后的日期
        if (end > twelveMonthsLater) {
          const adjustedEndDate = twelveMonthsLater.toISOString().split("T")[0]; // 转换为 yyyy-MM-dd 格式
          this.dateRange = [startDate, adjustedEndDate];

          // 手动调用接口请求逻辑
          this.fetchData([startDate, adjustedEndDate]);
          return; // 直接返回，避免重复调用
        }
      }

      // 如果日期范围为空，设置为空数组
      dateRange = dateRange || [];
      console.log("选择的日期范围：", dateRange);

      // 调用接口请求逻辑
      this.fetchData(dateRange);
    },
    fetchData(dateRange) {
      // 调用接口统计用户数量
      statisticsUserCount({
        end: dateRange[1] || "",
        start: dateRange[0] || "",
      }).then((response) => {
        this.userAllCount = response.data.data.userAllCount;
        this.userAuthCount = response.data.data.userAuthCount;
      });

      // 调用接口获取每日统计数据
      countListByDay({
        end: dateRange[1] || "",
        start: dateRange[0] || "",
      }).then((response) => {
        this.setChartData(response.data.data);
      });
    },
  },
};
</script>
  
  <style rel="stylesheet/scss" lang="scss" scoped>
.title {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 30px;
  margin-top: 30px;
}
.box-card {
  margin-bottom: 30px;
}

.dashboard-editor-container {
  padding: 32px;
  background-color: #f9f9f9;

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

.panel-group {
  margin-top: 18px;

  .card-panel-col {
    margin-bottom: 32px;
  }

  .card-panel {
    height: 108px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    // background: #f9f9f9;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05);
    border-color: rgba(0, 0, 0, 0.05);

    &:hover {
      .card-panel-icon-wrapper {
        color: #fff;
      }

      .icon-people {
        background: #40c9c6;
      }

      .icon-message {
        background: #36a3f7;
      }

      .icon-money {
        background: #f4516c;
      }

      .icon-shoppingCard {
        background: #34bfa3;
      }
    }

    .icon-people {
      color: #40c9c6;
    }

    .icon-message {
      color: #36a3f7;
    }

    .icon-money {
      color: #f4516c;
    }

    .icon-shoppingCard {
      color: #34bfa3;
    }

    .card-panel-icon-wrapper {
      float: left;
      margin: 14px 0 0 14px;
      padding: 16px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
    }

    .card-panel-icon {
      float: left;
      font-size: 48px;
    }

    .card-panel-description {
      text-align: center;
      font-weight: bold;
      margin: 26px;
      margin-left: 0px;

      .card-panel-text {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }

      .card-panel-num {
        font-size: 20px;
        color: #409eff;
      }
    }
  }
}
</style>
  